//
//  JKPicBrowserViewController.swift
//  JKWeibo
//
//  Created by albert on 16/6/23.
//  Copyright © 2016年 albert. All rights reserved.
//  图片浏览器

import UIKit
import SDWebImage
import SVProgressHUD

class JKPicBrowserViewController: UIViewController, JKBrowserCellDelegate {
    
    /** 所有缩略图配图URL */
    var thumbUrls: [NSURL]
    
    /** 所有大图配图URL */
    var bmiddlePicUrls: [NSURL]
    
    /** 当前点击的配图的索引 */
    var indexPath: NSIndexPath

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Right, animated: false)
    }
    
    // 布局完了之后再滚动到点击的那张图片的cell，使用viewWillLayoutSubviews也可以
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 下面这两个都可以，一样的效果
        collectionView.contentOffset = CGPoint(x: CGFloat(indexPath.item) * JKScreenW, y: 0)
        
        //collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Right, animated: false)
    }
    
    // 自定义构造方法
    init (thumbUrls: [NSURL], bmiddlePicUrls: [NSURL], indexPath: NSIndexPath) {
        
        self.thumbUrls = thumbUrls
        self.bmiddlePicUrls = bmiddlePicUrls
        self.indexPath = indexPath
        
        // 注意：自定义构造方法时，不一定是调用super.init(),需要调用当前类的设计构造方法（designated）
        super.init(nibName: nil, bundle: nil) // 因为两个属性是在这个方法中初始化的，所以要等着俩属性赋值初始化完毕后再调用这个设计构造方法
        //super.init()
        
        // 初始化UI
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 配图浏览器即将退出
    func browserCellWillDismiss(browserCell: JKBrowserCell) {
        closeButtonClick()
    }
    
    // MARK: - 内部控制方法
    /** 初始化UI */
    private func setupUI() {
        // 1.添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 2.布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView" : collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView" : collectionView])
        view.addConstraints(cons)
        
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        var closeCons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-30-[closeButton(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["closeButton" : closeButton])
        closeCons += NSLayoutConstraint.constraintsWithVisualFormat("V:[closeButton(30)]-30-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["closeButton" : closeButton])
        view.addConstraints(closeCons)
        
        
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        var saveCons = NSLayoutConstraint.constraintsWithVisualFormat("H:[saveButton(100)]-30-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["saveButton" : saveButton])
        saveCons += NSLayoutConstraint.constraintsWithVisualFormat("V:[saveButton(30)]-30-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["saveButton" : saveButton])
        view.addConstraints(saveCons)
    }
    
    /** 关闭 */
    @objc private func closeButtonClick() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /** 保存 */
    @objc private func saveButtonClick() {
        let cell = collectionView.visibleCells().last as! JKBrowserCell
        let key = cell.bmiddleUrl?.absoluteString
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            
            SVProgressHUD.showErrorWithStatus("正在加载图片...请稍等")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            
            return
        }
        
        //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func image (image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject?) {
        
        SVProgressHUD.showWithStatus("正在保存...")
        
        if didFinishSavingWithError != nil {
            SVProgressHUD.showErrorWithStatus("正在加载图片...请稍等")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("保存图片成功！")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
        JKDispatchTool.after(JKTipDuration) { () -> Void in
            SVProgressHUD.dismiss()
        }
    }
    
    // MARK: - 懒加载
    /** collectionView */
    lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: JKBrowserLayout())
        
        clv.dataSource = self
        clv.delegate = self
        clv.registerClass(JKBrowserCell.self, forCellWithReuseIdentifier: "browserCell")
        
        return clv
    }()
    
    /** 关闭按钮 */
    private lazy var closeButton: UIButton = {
        let btn = UIButton(type: UIButtonType.Custom)
        
        btn.setTitle("关 闭", forState: UIControlState.Normal)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.addTarget(self, action: "closeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    /** 保存按钮 */
    private lazy var saveButton: UIButton = {
        let btn = UIButton(type: UIButtonType.Custom)
        
        btn.setTitle("保 存", forState: UIControlState.Normal)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.addTarget(self, action: "saveButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
}

// MARK: - 数据源
extension JKPicBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bmiddlePicUrls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let thumbUrl = thumbUrls[indexPath.item]
        let bmiddleUrl = bmiddlePicUrls[indexPath.item]
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("browserCell", forIndexPath: indexPath) as! JKBrowserCell
        
        cell.thumbUrl = thumbUrl
        cell.bmiddleUrl = bmiddleUrl
        
        cell.delegate = self
        
        return cell
    }
}

// MARK: - 自定义流水布局
class JKBrowserLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        
        // 1.cell尺寸，只能使用屏幕尺寸，使用collectionView的尺寸会出错
        itemSize = JKScreenBounds.size
        
        // 2.cell间距
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        // 3.滚动方向
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 4.分页
        collectionView?.pagingEnabled = true
        
        // 5.去除弹簧效果
        collectionView?.bounces = false
        
        // 6.去除滚动条
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}
